package com.sdp.khy.baotou.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sdp.core.bizc.db.Query;
import com.sdp.core.bizc.redis.RedisUtil;
import com.sdp.core.bizc.utils.TokenUtils;
import com.sdp.core.bizc.vo.BusinessContext;
import com.sdp.core.bizc.vo.DataCenter;
import com.sdp.core.bizc.vo.Result;
import com.sdp.khy.baotou.SendSms.SendSmsController;
import com.sdp.khy.baotou.db.khy_banner.entity.KhyBanner;
import com.sdp.khy.baotou.db.khy_banner.service.IKhyBannerService;
import com.sdp.khy.baotou.db.khy_companies_desc.entity.KhyCompaniesDesc;
import com.sdp.khy.baotou.db.khy_companies_desc.service.IKhyCompaniesDescService;
import com.sdp.khy.baotou.db.khy_coupon_scheme.entity.KhyCouponScheme;
import com.sdp.khy.baotou.db.khy_coupon_scheme.service.IKhyCouponSchemeService;
import com.sdp.khy.baotou.db.khy_emp.entity.KhyEmp;
import com.sdp.khy.baotou.db.khy_emp.service.IKhyEmpService;
import com.sdp.khy.baotou.db.khy_line_info.entity.KhyLineInfo;
import com.sdp.khy.baotou.db.khy_line_info.service.IKhyLineInfoService;
import com.sdp.khy.baotou.db.khy_notice.entity.KhyNotice;
import com.sdp.khy.baotou.db.khy_notice.service.IKhyNoticeService;
import com.sdp.khy.baotou.db.khy_param_info.entity.KhyParamInfo;
import com.sdp.khy.baotou.db.khy_price_info.entity.KhyPriceInfo;
import com.sdp.khy.baotou.db.khy_price_info.service.IKhyPriceInfoService;
import com.sdp.khy.baotou.db.khy_protect_price_pact.entity.KhyProtectPricePact;
import com.sdp.khy.baotou.db.khy_protect_price_pact.service.IKhyProtectPricePactService;
import com.sdp.khy.baotou.db.khy_service_qa.entity.KhyServiceQa;
import com.sdp.khy.baotou.db.khy_service_qa.service.IKhyServiceQaService;
import com.sdp.khy.baotou.db.khy_station.entity.KhyStation;
import com.sdp.khy.baotou.db.khy_station.service.IKhyStationService;
import com.sdp.khy.baotou.db.khy_supervision_info.entity.KhySupervisionInfo;
import com.sdp.khy.baotou.db.khy_supervision_info.service.IKhySupervisionInfoService;
import com.sdp.khy.baotou.db.khy_transport_pact.entity.KhyTransportPact;
import com.sdp.khy.baotou.db.khy_transport_pact.service.IKhyTransportPactService;
import com.sdp.khy.baotou.db.khy_user.entity.KhyUser;
import com.sdp.khy.baotou.db.khy_user.service.IKhyUserService;
import com.sdp.khy.baotou.db.khy_user_coupon.entity.KhyUserCoupon;
import com.sdp.khy.baotou.db.khy_user_coupon.service.IKhyUserCouponService;
import com.sdp.khy.baotou.utils.KhyConstants;
import com.sdp.khy.baotou.view.UserView;
import com.sdp.right.db.sys_dict.service.ISysDictService;
import com.sdp.right.db.sys_emp.service.ISysEmpService;
import com.sdp.right.entity.SysEmp;
import com.sdp.right.utils.RightConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/HomeController")
public class HomeController {

	@Autowired
	private IKhyBannerService bannerService;

	@Autowired
	private IKhyNoticeService noticeService;

	@Autowired
	private IKhyLineInfoService lineInfoService;

	@Autowired
	private IKhyStationService stationService;

	@Autowired
	private IKhyProtectPricePactService pricePactService;

	@Autowired
	private IKhyTransportPactService transportPactService;

	@Autowired
	private IKhyCompaniesDescService companiesDescService;

	@Autowired
	private IKhyServiceQaService serviceQaService;

	@Autowired
	private IKhyUserService iKhyUserService;

	@Autowired
	private ISysEmpService iSysEmpService;

	@Autowired
	private IKhyEmpService iKhyEmpService;
	
	@Autowired
	private IKhyPriceInfoService khyPriceInfoService;
	
	@Autowired
	private IKhySupervisionInfoService khySupervisionInfoService;
	
	@Autowired
	private IKhyCouponSchemeService couponSchemeService;
	
	@Autowired
	private IKhyUserCouponService userCouponService;

	@Autowired
	HttpServletRequest request;

	@Autowired
	private Query query;

	@Autowired
	private RedisUtil redisUtil;

	@Value("${sdp.rightMode}")
	private boolean rightMode;

	@Autowired
	private ISysDictService iSysDictService;

	@GetMapping(value = "/getDictData")
	public Result<?> getDictData(@RequestParam(name="dictCode",required=true) String dictCode,
			@RequestParam(name="dictParam",required=false) String dictParam) {
		JSONObject dictInfo = new JSONObject();
		if(!StringUtils.isEmpty(dictCode)) {
			String arg [] = {};
			if(!StringUtils.isEmpty(dictParam) && dictParam.length()>0) {
				arg = dictParam.split(",");
			}
			String[] dictCodes = dictCode.split(",");
			for(int i=0;i<dictCodes.length;i++) {
				dictInfo.put(dictCodes[i], iSysDictService.getDictInfo(dictCodes[i],arg));
			}
		}
		return Result.ok(dictInfo);
	}

	@GetMapping(value = "/getCompanyDesc")
	public Result<?> getCompanyDesc() {
		QueryWrapper<KhyCompaniesDesc> queryWrapper = new QueryWrapper<>();
		return Result.ok(companiesDescService.getOne(queryWrapper, false));
	}

	@GetMapping(value = "/getHomeData")
	public Result<?> getHomeData() {
		QueryWrapper<KhyBanner> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(KhyBanner::getIsUse, KhyConstants.是.getCode())
			.orderByAsc(KhyBanner::getBannerOrder);
		List<KhyBanner> bannerList = bannerService.list(queryWrapper);

		QueryWrapper<KhyNotice> queryWrapperNotice = new QueryWrapper<KhyNotice>();
		queryWrapperNotice.lambda().eq(KhyNotice::getIsUse, KhyConstants.是.getCode()).orderByDesc(KhyNotice::getSendTime);
		queryWrapperNotice.last("limit 3");
		List<KhyNotice> noticeList = noticeService.list(queryWrapperNotice);

		Map<String, Object> result = new HashMap<>();
		result.put(KhyBanner.class.getSimpleName(), bannerList);
		result.put(KhyNotice.class.getSimpleName(), noticeList);
		return Result.ok(result);
	}

	@GetMapping(value = "/getBanner")
	public Result<?> getBanner() {
		QueryWrapper<KhyBanner> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(KhyBanner::getIsUse, KhyConstants.是.getCode())
			.orderByAsc(KhyBanner::getBannerOrder);
		return Result.ok(bannerService.list(queryWrapper));
	}

	@GetMapping(value = "/getNoticeTop3")
	public Result<?> getNoticeTop3() {
		QueryWrapper<KhyNotice> queryWrapper = new QueryWrapper<KhyNotice>();
		queryWrapper.lambda().eq(KhyNotice::getIsUse, KhyConstants.是.getCode()).orderByDesc(KhyNotice::getSendTime);
		queryWrapper.last("limit 3");
		return Result.ok(noticeService.list(queryWrapper));
	}

	@PostMapping(value = "/pageNotice")
	public Result<?> pageNotice(@RequestBody DataCenter dataCenter) {
		QueryWrapper<KhyNotice> queryWrapper = new QueryWrapper<KhyNotice>();
		queryWrapper.lambda().eq(KhyNotice::getIsUse, KhyConstants.是.getCode()).orderByDesc(KhyNotice::getSendTime);
		return Result.ok(query.page(noticeService, KhyNotice.class, dataCenter, queryWrapper));
	}

	@GetMapping(value = "/getLineList")
	public Result<?> getLineList() {
		QueryWrapper<KhyLineInfo> queryWrapper = new QueryWrapper<KhyLineInfo>();
		queryWrapper.lambda().eq(KhyLineInfo::getUseSet, KhyConstants.是.getCode());
		return Result.ok(lineInfoService.list(queryWrapper));
	}

	@GetMapping(value = "/getStationList")
	public Result<?> getStationList() {
		QueryWrapper<KhyStation> queryWrapper = new QueryWrapper<KhyStation>();
		queryWrapper.lambda().orderByAsc(KhyStation::getStationOrder);
		return Result.ok(stationService.list(queryWrapper));
	}
	
	/*
	 * 计费标准
	 */
	@GetMapping(value = "/getPriceInfo")
	public Result<?> getPriceInfo() {
		return Result.ok(khyPriceInfoService.getOne(new QueryWrapper<KhyPriceInfo>(), false));
	}
	
	/*
	 * 咨询及监督
	 */
	@GetMapping(value = "/getSupervisionInfo")
	public Result<?> getSupervisionInfo() {
		return Result.ok(khySupervisionInfoService.getOne(new QueryWrapper<KhySupervisionInfo>(), false));
	}

	/*
	 * 货物保价约定
	 */
	@GetMapping(value = "/getPricePact")
	public Result<?> getPricePact() {
		return Result.ok(pricePactService.getOne(new QueryWrapper<KhyProtectPricePact>(), false));
	}

	/*
	 * 货物托运约定
	 */
	@GetMapping(value = "/getTransportPact")
	public Result<?> getTransportPact() {
		return Result.ok(transportPactService.getOne(new QueryWrapper<KhyTransportPact>(), false));
	}

	/*
	 * 客服信息
	 */
	@GetMapping(value = "/getServiceQaList")
	public Result<?> getServiceQaList() {
		QueryWrapper<KhyServiceQa> queryWrapper = new QueryWrapper<KhyServiceQa>();
		queryWrapper.lambda().eq(KhyServiceQa::getIsUse, KhyConstants.是.getCode())
			.orderByAsc(KhyServiceQa::getQuestionOrder);
		return Result.ok(serviceQaService.list(queryWrapper));

	}
	
	/*
	 * 获取当前登录人信息
	 */
	@GetMapping(value = "/getKhyUser")
	public Result<?> getKhyUser(@RequestParam(name="userNo",required=true) String userNo) {
		QueryWrapper<KhyUser> queryWrapper = new QueryWrapper<KhyUser>();
		queryWrapper.lambda().eq(KhyUser::getUserNo, userNo);
		return Result.ok(iKhyUserService.getOne(queryWrapper, false));
	}

	/**
	 * 大众手机号注册
	 * @param khyUsers
	 * @return
	 */
	@PostMapping(value = "/saveKhyUser")
	@Transactional(rollbackFor = Exception.class)
	public Result<?> saveKhyUser(@RequestBody KhyUser khyUsers)  {
         if(StringUtils.isEmpty(khyUsers.getUserNo())){
         	return  Result.error("手机号为空");
		 }
         QueryWrapper<KhyUser> queryWrapper=new QueryWrapper<>();
		 queryWrapper.lambda().eq(KhyUser::getUserNo,khyUsers.getUserNo());
		 KhyUser khyUser= iKhyUserService.getOne(queryWrapper);
		 if(khyUser != null){
			 return  Result.error("手机号已注册");
		 }
		Object  code=	redisUtil.get(khyUsers.getUserNo());
		if(StringUtils.isEmpty(code)){
			return  Result.error("验证码已过期");
		}
		if(!khyUsers.getVerifyCode().equals(code.toString())){
			return  Result.error("验证码错误");
		}
		khyUsers.setUserPwd(khyUsers.getUserPwd());
		khyUsers.setIsUse(KhyConstants.是.getCode());
		khyUsers.setIsNew(KhyConstants.是.getCode());//是否是新用户
		khyUsers.setCreateTime(LocalDateTime.now());
		iKhyUserService.save(khyUsers);
		//添加新人注册的优惠卷
		QueryWrapper<KhyCouponScheme> queryWrapperScheme = new QueryWrapper<>();
		queryWrapperScheme.lambda().eq(KhyCouponScheme::getSchemeType, KhyConstants.优惠卷方案类型_新用户.getCode())
			.eq(KhyCouponScheme::getUseSet, KhyConstants.是.getCode())
			.gt(KhyCouponScheme::getEndDate, LocalDate.now());
		List<KhyCouponScheme> list = couponSchemeService.list(queryWrapperScheme);
		List<KhyUserCoupon> insertList = new ArrayList<>();
		LocalDateTime currentTime = LocalDateTime.now();
		for (KhyCouponScheme khyCouponScheme : list) {
			if (!StringUtils.isEmpty(khyCouponScheme.getPerCount())) {
				int num = Integer.parseInt(khyCouponScheme.getPerCount());
				for (int i = 0; i < num; i++) {
					KhyUserCoupon userCoupon = new KhyUserCoupon();
					userCoupon.setCouponName(khyCouponScheme.getCouponName());
					userCoupon.setCouponStatus(KhyConstants.优惠卷状态_可使用.getCode());
					userCoupon.setCouponType(khyCouponScheme.getCouponType());
					userCoupon.setCouponValue(khyCouponScheme.getCouponValue());
					userCoupon.setCreateTime(currentTime);
					userCoupon.setEndDate(khyCouponScheme.getEndDate());
					userCoupon.setSchemeId(khyCouponScheme.getKeyId());
					userCoupon.setUserNo(khyUsers.getUserNo());
					insertList.add(userCoupon);
				}
			}
		}
		userCouponService.saveBatch(insertList);
		return Result.ok();
	}
	/**
	 * 大众手机号忘记密码
	 * @param khyUsers
	 * @return
	 */
	@PostMapping(value = "/updateKhyUser")
	public Result<?> updateKhyUser(@RequestBody KhyUser khyUsers)  {
		if(StringUtils.isEmpty(khyUsers.getUserNo())){
			return  Result.error("手机号为空");
		}
		QueryWrapper<KhyUser> queryWrapper=new QueryWrapper<>();
		queryWrapper.lambda().eq(KhyUser::getUserNo,khyUsers.getUserNo());
		KhyUser khyUser= iKhyUserService.getOne(queryWrapper);
		if(khyUser == null){
			return  Result.error("手机号未注册");
		}
		Object  code=	redisUtil.get(khyUsers.getUserNo());
		if(StringUtils.isEmpty(code)){
			return  Result.error("验证码已过期");
		}
		if(!khyUsers.getVerifyCode().equals(code.toString())){
			return  Result.error("验证码错误");
		}
		khyUser.setUserPwd(khyUsers.getUserPwd());
		iKhyUserService.updateById(khyUser);
		return Result.ok();
	}
	/**
	 * 登陆 /// 优先查询权限大的表
	 * @param sysEmp
	 * DynamicDataSourceContextHolder.push(ds);
	 * @return
	 * @throws Exception
	 */
	@PostMapping(value = "/login")
	public Result<?> login(@RequestBody SysEmp sysEmp){
		BusinessContext businessContext = logins(sysEmp);
		if(businessContext.isSuccess()) {
			// 最高权限
			JSONObject permissionInfo = new JSONObject();
			permissionInfo.put("userInfo", businessContext.get("userInfo"));
			return Result.ok(permissionInfo);
		}
		return Result.error(businessContext.getMessage());
	}
	public BusinessContext logins(SysEmp sysEmp)  {
		BusinessContext businessContext = new BusinessContext();
		if(sysEmp==null || StringUtils.isEmpty(sysEmp.getAccountNo()) || StringUtils.isEmpty(sysEmp.getEmpPwd())) {
			businessContext.setSuccess(false);
			businessContext.setMessage("账号或密码为空");
			return businessContext;
		}
		QueryWrapper<SysEmp> sysEmpQueryWrapper=new QueryWrapper<>();
		sysEmpQueryWrapper.lambda().eq(SysEmp::getAccountNo,sysEmp.getAccountNo())
				                   .eq(SysEmp::getEmpPwd,sysEmp.getEmpPwd());
		SysEmp sysEmp1=iSysEmpService.getOne(sysEmpQueryWrapper);
		if(sysEmp1 == null){
			QueryWrapper<KhyUser> queryWrapper=new QueryWrapper<>();
			queryWrapper.lambda().eq(KhyUser::getUserNo,sysEmp.getAccountNo())
					.eq(KhyUser::getUserPwd,sysEmp.getEmpPwd());
			KhyUser khyUser = iKhyUserService.getOne(queryWrapper);
			if(khyUser==null) {
				businessContext.setSuccess(false);
				businessContext.setMessage("账号或密码错误");
				return businessContext;
			}else if(khyUser.getIsUse().equals(RightConstants.否.getCode())){
				businessContext.setSuccess(false);
				businessContext.setMessage("账号已锁定");
				return businessContext;
			}


			boolean isSet = redisUtil.setMap(KhyUser.class, khyUser.getUserNo(), khyUser);
			if(!isSet) {
				businessContext.setSuccess(false);
				businessContext.setMessage("缓存服务失败");
				return businessContext;
			}
			UserView userView=new UserView();
			userView.setUserNo(khyUser.getUserNo());
			userView.setUserType(KhyConstants.用户类型_大众.getCode());
			userView.setEmpPost(KhyConstants.用户类型_大众.getCode());
			userView.setToken(TokenUtils.token(khyUser.getUserNo(),khyUser.getUserPwd(),khyUser.getUserNo(),khyUser.getUserPwd()));
			businessContext.setSuccess(true);
			businessContext.put("userInfo",userView);
			return businessContext;
		}else if(sysEmp1.getIsUse().equals(RightConstants.否.getCode())){
			businessContext.setSuccess(false);
			businessContext.setMessage("账号已锁定");
			return businessContext;
		}
		QueryWrapper<KhyEmp> queryWrapper=new QueryWrapper<>();
		queryWrapper.lambda().eq(KhyEmp::getAccountNo,sysEmp.getAccountNo());
		KhyEmp khyEmp = iKhyEmpService.getOne(queryWrapper);
		boolean isSet = redisUtil.setMap(SysEmp.class, sysEmp1.getAccountNo(), sysEmp1);
		if(!isSet) {
			businessContext.setSuccess(false);
			businessContext.setMessage("缓存服务失败");
			return businessContext;
		}
		//生成token
		UserView userView=new UserView();
		userView.setUserNo(khyEmp.getEmpNo());
		userView.setUserName(khyEmp.getEmpName());
		userView.setUserType(khyEmp.getEmpPost());
		userView.setEmpPost(khyEmp.getEmpPost());
		userView.setStationId(khyEmp.getStationId());
		userView.setToken(TokenUtils.token(sysEmp1.getAccountNo(),sysEmp1.getEmpPwd(),sysEmp1.getEmpNo(),sysEmp1.getEmpName()));
		businessContext.setSuccess(true);
		businessContext.put("userInfo",userView);
		return businessContext;
	}
	@PostMapping(value = "/upPassword")
	public Result<?> upPassword(@RequestBody SysEmp sysEmp) {
        QueryWrapper<SysEmp> sysEmpQueryWrapper=new QueryWrapper<>();
		sysEmpQueryWrapper.lambda().eq(SysEmp::getAccountNo,sysEmp.getAccountNo());
		SysEmp sysEmp1=iSysEmpService.getOne(sysEmpQueryWrapper);
		if(sysEmp1!= null){
			sysEmp1.setEmpPwd(sysEmp.getEmpPwd());
			iSysEmpService.updateById(sysEmp1);

		}else{
			QueryWrapper<KhyUser> khyUserQueryWrapper=new QueryWrapper<>();
			khyUserQueryWrapper.lambda().eq(KhyUser::getUserNo,sysEmp.getAccountNo());
			KhyUser khyUser=iKhyUserService.getOne(khyUserQueryWrapper);
			if(khyUser!= null){
				khyUser.setUserPwd(sysEmp.getEmpPwd());
				iKhyUserService.updateById(khyUser);
			}else{
				return Result.error("用户不存在");
			}
		}
		return Result.ok();
	}

	/**
	 * 获取验证码
	 * @param jsonObject
	 * @return
	 */
	@PostMapping(value = "/getSmsCode")
	public Result<?> getSmsCode(@RequestBody JSONObject jsonObject) {
		try {
				String code=SendSmsController.sendSms(jsonObject);
				 if(StringUtils.isEmpty(code)){
				 	return Result.error("获取失败，请稍后重试");
				 }
				 redisUtil.set(jsonObject.get("phoneNumbers").toString(),code, 300);
			return Result.ok();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return Result.ok();
	}
	
	/**
	 * 获取参数信息
	 * @return
	 */
	@GetMapping(value = "/getParamInfo")
	public Result<?> getParamInfo() {
		List<KhyParamInfo> paramList = redisUtil.get(KhyParamInfo.class);
		return Result.ok(paramList);
	}
	
}
